const cloud = require('wx-server-sdk')
cloud.init()

exports.main = async (event, context) => {
  try {
    const { OPENID } = cloud.getWXContext()
    const db = cloud.database()
    // 获取用户信息
    let user = await db
      .collection('user')
      .where({
        openid: OPENID,
      })
      .get()

    // 获取订阅信息
    let subscribe = 0
    let message = await db
      .collection('messages')
      .where({
        touser: OPENID,
        templateId: event.templateId,
      })
      .get()

    if (message.data.length == 1 && !message.data[0].done) {
      subscribe = 1
    }

    let userInfo = {}
    if (user.data.length) {
      userInfo = user.data[0]
    }

    userInfo.subscribe = subscribe
    return userInfo
  } catch (err) {
    console.log(err)
    return err
  }
}
